/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package util;

import java.io.*;
import com.hp.hpl.jena.query.*;

/**
 *
 * @author antonio
 */

// quando si implementerà il parsing dalla riga di comando ricordarsi che di devono passare
// l'URI dell'utente ed il server che ospita i grafi che serviranno per effettuare le query
// magari si mettono in un hash e quandi ci servono le tiriamo fuori.

public class UpdaterVirtuosoPosition {

    private String electedPoint;
    private String actualPosition;

    public UpdaterVirtuosoPosition(String electedPoint, String actualPosition)
    {
        this.electedPoint = electedPoint;
        this.actualPosition = actualPosition;
    }

    public void update()
    {
        String oldValue = "";

        String risultato = "";

        String testoQuery = "select ?stanza from <http://localhost:8890/DAV/thecubix> where" +
                "{<http://unime.it/thecubix/CaristiaAntonio> <http://unime.it/cubixprop#nelAula> ?stanza}";

       
        String comando = "isql";


        Query cubixQuery = QueryFactory.create(testoQuery);
        ResultSet results;

        QueryExecution qexec = QueryExecutionFactory.sparqlService("http://localhost:8890/sparql", cubixQuery);

        results = qexec.execSelect();

        for( ; results.hasNext(); )
        {
            QuerySolution soln = results.nextSolution();
            System.out.print("Update Virtuoso Position: ");

            oldValue = soln.get("stanza").toString();
            System.out.print("OLD POSITION = " + oldValue);
            System.out.print("\n\n");

        }

        String testoModify = "sparql " +
                "MODIFY GRAPH <http://localhost:8890/DAV/thecubix> " +
                "DELETE " +
                "{<http://unime.it/thecubix/CaristiaAntonio> " +
                "<http://unime.it/cubixprop#nelAula>  \"" + oldValue + "\" } " +
                "INSERT " +
                "{<http://unime.it/thecubix/CaristiaAntonio>  <http://unime.it/cubixprop#nelAula> \"" + this.actualPosition + "\" };";
        

        try {
            Runtime r = Runtime.getRuntime();
            Process p = r.exec(comando);

            PrintWriter o = new PrintWriter(p.getOutputStream(), true);
            o.println(testoModify);

            BufferedReader in = new BufferedReader(new InputStreamReader( p.getInputStream() ));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {

                System.out.println(inputLine);
                risultato += inputLine;
            }

            System.out.println(risultato);

        }catch (IOException e){

            System.out.println(e);

        }

    }


}
